<template>
  <div class="mb-4">
    <el-button type="success" class="edit" @click="addUser">新增用户</el-button>
    <el-button type="danger" class="edit" @click="batchDelUser">批量删除</el-button>
  </div>

<!--弹窗  -->
  <el-dialog v-model="dialogFormVisible" :title="userQuery.id > 0 ? '编辑用户' : '新增用户'" width="500" style="text-align: center">
    <el-form :model="userQuery" :rules="dialogFormRules" ref="dialogRef">

      <el-form-item label="账号" prop="loginAct">
        <el-input v-model="userQuery.loginAct" />
      </el-form-item>
      <el-form-item label=" 密码" v-if="userQuery.id > 0" >
        <el-input type="password" v-model="userQuery.loginPwd" disabled/>
      </el-form-item>

      <el-form-item label="密码" prop="loginPwd" v-else>
        <el-input  v-model="userQuery.loginPwd" /><!--type="password"-->
      </el-form-item>

      <el-form-item label="手机" prop="phone">
        <el-input v-model="userQuery.phone" />
      </el-form-item>

      <el-form-item label="姓名" prop="name">
        <el-input v-model="userQuery.name" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userQuery.email" />
      </el-form-item>

      <el-form-item label="账号未过期" prop="accountNoExpired">
        <el-radio-group v-model="userQuery.accountNoExpired" class="ml-4">
          <el-radio :label="1" size="large" >是</el-radio>
          <el-radio :label="0" size="large" >否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="密码未过期" prop="credentialsNoExpired">
        <el-radio-group v-model="userQuery.credentialsNoExpired" class="ml-4">
          <el-radio :label="1" size="large">是</el-radio>
          <el-radio :label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="账号未锁定" prop="accountNoLocked">
        <el-radio-group v-model="userQuery.accountNoLocked" class="ml-4">
          <el-radio :label="1" size="large">是</el-radio>
          <el-radio :label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="账号是否启用" prop="accountEnabled">
        <el-radio-group v-model="userQuery.accountEnabled" class="ml-4">
          <el-radio :label="1" size="large">是</el-radio>
          <el-radio :label="0" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUser">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>



  <el-table :data="userList"
            style="width: 100%"
            @selection-change="selectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="80"/>
    <el-table-column property="loginAct" label="账号" />
    <el-table-column property="phone" label="手机" />
    <el-table-column property="name" label="姓名" />
    <el-table-column property="email" label="邮箱"/>
    <el-table-column property="createTime" label="创建时间" show-overflow-tooltip/>
    <el-table-column label="操作">
<!--使用插槽获取用户信息-->
      <template #default="scope">
        <el-button type="primary" @click="details(scope.row.id)">详情</el-button>
        <el-button type="success" @click="editUser(scope.row.id)">编辑</el-button>
        <el-button type="danger" @click="delUser(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <p></p>
  <p></p>
  <p></p>
    <el-pagination
        class="page"
        background
        :page-size=pageSize
        layout="prev, pager, next"
        @current-change="page"
        @prev-click="page"
        @next-click="page"
        :total=total />
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "@/http/httpRequest";
import {confirmMessageTip, messageTip} from "@/util/utils";

export default {
  name:"UserView",
  data(){
    return{
      userList:[{}],
      pageSize:0,
      total:0,
      dialogFormVisible : false,
      userQuery : {},
      userIdArray:[],
      dialogFormRules : {
        loginAct: [
            {required:true, message: "请输入", trigger:'blur'}
          ],
        loginPwd: [
          {required:true, message: "请输入", trigger:'blur'},
          {min:6, max:16, message: "密码长度6-16位", trigger:'blur'}
        ],
        phone: [
          {required:true, pattern:/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: "请输入正确的手机号", trigger:'blur'}
        ],
        name: [
          {required:true, message: "请输入", trigger:'blur'}
        ],
        email: [
          {required:true, pattern:/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/ , message: "请输入正确的邮箱", trigger:'blur'}
        ],
        accountNoExpired: [
          {required:true, message: "请输入", trigger:'blur'}
        ],
        credentialsNoExpired: [
          {required:true, message: "请输入", trigger:'blur'}
        ],
        accountNoLocked: [
          {required:true, message: "请输入", trigger:'blur'}
        ],
        accountEnabled: [
          {required:true, message: "请输入", trigger:'blur'}
        ]
      },
    }
  },
  //父页面的函数使用
  inject:['reload'],
  methods:{
    selectionChange(dataArray) {
       // alert(JSON.stringify(data.get(id)))
      this.userIdArray = [],
      dataArray.forEach(data =>{
        this.userIdArray.push(data.id)
      })
    },
    getUserInfo(current){
      doGet("/api/getUsers",{
        current:current
      }).then(res =>{
        if (res.data.code === 200) {
          this.userList = res.data.data.list;
          this.total = res.data.data.total;
          this.pageSize = res.data.data.pageSize;
        }
      })
    },
    page(number) {
      this.getUserInfo(number)
    },
    details(id) {
      //跳转路由
      this.$router.push('/hello/user/' + id)
    },
    addUser(){
      this.userQuery = {};
      this.dialogFormVisible = true;
    },
    submitUser() {
      //编辑和新增的公用
      this.$refs.dialogRef.validate( (valid) =>{
            if (valid) {
              let formdata = new FormData();
              for (let userData in this.userQuery) {
                formdata.append(userData, this.userQuery[userData])
              }

              if(this.userQuery.id > 0){
                doPut('api/editUser', formdata).then( res => {
                  if (res.data.code === 200) {
                    //提示信息
                    messageTip("编辑用户成功", "success")
                    //刷新页面
                    this.reload();
                  }else {
                    messageTip("添加用户失败！原因是：" + res.data.msg, "error")
                  }
                })
              }else {
                //发送请求
                doPost('api/addUser', formdata).then( res => {
                  if (res.data.code === 200) {
                    //提示信息
                    messageTip("添加用户成功", "success")
                    //刷新页面
                    this.reload();
                  }else {
                    messageTip("添加用户失败！原因是：" + res.data.msg, "error")
                  }
                });

              }
            }
      })

    },

    editUser(userId){
        //编辑，新增共用一个弹窗。
      this.dialogFormVisible = true;
      //获取用户信息
      this.userDetail(userId);
    },
    /**
     * 删除用户
     * @param userId
     */
    delUser(userId) {
      confirmMessageTip('确认删除此用户吗？').then(() => {
        //删除用户
        doDelete("api/delUser/" + userId,{}).then(res =>{
          if (res.data.code === 200) {
            messageTip("删除成功", "success")
            //刷新
            this.reload();
          }else {
            messageTip(res.data.msg,"error")
          }
        })
      }).catch(() => {
            messageTip("取消", "info")
          })
    },
    /**
     * 批量删除
     */
    batchDelUser() {
      if (this.userIdArray.length === 0){
        messageTip("请选择需要删除的用户！", "warning")
      }else {

        //批量删除用户
        confirmMessageTip('您确定要删除当前选中用户吗？').then(() => {
          let ids = this.userIdArray.join(",")
          doDelete("api/userDelBatch",{ids:ids}).then(res =>{
            if (res.data.code === 200){
              messageTip("删除成功", "success")
              this.reload();
            }else {
              messageTip("删除失败，原因是：" + res.data.msg, "error")
              this.reload();
            }
          })
        }).catch(()=>{
          messageTip("取消","warning")
        })
      }
    },
    /**
     * 获取用户信息
     * @param id
     */
    userDetail(id) {
      doGet("api/userDetail/" + id, {}).then(res =>{
        if (res.data.code === 200) {
          this.userQuery = res.data.data;
        }
      })
    },

  },
  mounted() {
    //分页 默认第一页
    this.getUserInfo(1);
  }
}
</script>


<style scoped>
.edit{
  margin-bottom: 15px;
}

.page{
  display: flex;
  justify-content: center;
}
</style>